<template>
  <el-dialog
    v-model="dialogVisible"
    title="设置开关列可见性"
    width="400px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules">
      <el-form-item label="开关列可见性" prop="enabled">
        <el-switch v-model="form.enabled" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="success" :loading="submitLoading" @click="handleConfirm">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { updateColumnVisibilityEnabled } from "@/api/adminThirdPartyApi";
import { message } from "@/utils/message";
import type { FormRules } from "element-plus";

const dialogVisible = ref(false);
const id = ref(null);
interface RuleForm {
  enabled: boolean;
}
const form = ref<RuleForm>({
  enabled: true
});
const rules = reactive<FormRules<RuleForm>>({
  enabled: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ]
});

const serviceForm = ref(null);
const resetForm = () => {
  serviceForm.value?.resetFields();
  serviceForm.value?.clearValidate();
};
const submitLoading = ref(false);
const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    try {
      if (valid) {
        submitLoading.value = true;
        await updateColumnVisibilityEnabled(id.value, form.value);
        message("操作成功", { type: "success" });
        dialogVisible.value = false;
      }
    } finally {
      submitLoading.value = false;
    }
  });
};
const open = (ids: number | string, enabled: boolean) => {
  id.value = ids;
  form.value.enabled = enabled;
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
